<template>
  <div>
    <slot></slot>

    <div ref="loadingTarget" class="h-6 py-4">
      <!-- 加载更多 -->
      <m-svg-icon
        v-show="loading"
        class="w-4 h-4 mx-auto animate-spin bg-gray-900"
        name="infinite-load"
      ></m-svg-icon>
      <!-- 没有更多数据 -->
      <p v-if="isFinished" class="text-center text-base text-zinc-400">
        没有更多数据了！
      </p>
    </div>
  </div>
</template>

<script setup>
import { useVModel, useIntersectionObserver } from '@vueuse/core'
import { ref, watch } from 'vue'

const props = defineProps({
  modelValue: {
    type: Boolean,
    required: true
  },
  isFinished: {
    type: Boolean,
    default: false
  }
})

const emits = defineEmits(['onLoad', 'update:modelValue'])
const loading = useVModel(props)
const targetIsintersecting = ref(false)

const loadingTarget = ref(null)
useIntersectionObserver(loadingTarget, ([{ isIntersecting }]) => {
  // 当加载更多视图可见时触发
  targetIsintersecting.value = isIntersecting
  emitLoad()
})

const emitLoad = () => {
  if (targetIsintersecting.value && !loading.value && !loading.isFinished) {
    loading.value = true
    emits('onLoad')
  }
}

watch(loading, emitLoad)
</script>

<style></style>
